import { put, delay, cancel, fork, take, takeLatest } from 'redux-saga/effects'
import { actionTypes, increase } from '../action/counter'


let task
function* autoIncrease() {
    while (true) {
        yield take(actionTypes.autoIncrease)
        yield* stop()
        task = yield fork(function* () {
            while (true) {
                yield delay(2000)
                yield put(increase())
            }
        })
    }
}

function* stop() {
    if (task) {
        yield cancel(task)
    }
}

function* stopAutoIncrease() {
    yield* stop()
}

export default function* () {
    yield takeLatest(actionTypes.stopAutoIncrease, stopAutoIncrease)
    yield fork(autoIncrease)
}